package com.shadow.demo.dictionary.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Json辅助工具类
 *
 * @author penggch
 */
public class JsonUtil {

    /**
     * 对象序列化为JSON字符串
     *
     * @param object 对象
     * @return JSON字符串
     */
    public static String serialize(Object object) {
        return BeanUtil.serialize(object);
    }

    /**
     * JSON字符串反序列化为对象
     *
     * @param <T>     对象泛型类型
     * @param content JSON字符串
     * @param cls     对象类型（不能是接口，需要使用实现类）
     * @return
     */
    public static <T> T deserialize(String content, Class<T> cls) {
        return BeanUtil.deserialize(content, cls);
    }

    /**
     * 反序列化List
     *
     * @param <T>
     * @param content json字符串
     * @param cls     目标类型
     * @return
     */
    public static <T> List<T> deserializeList(String content, Class<T> cls) {
        List<T> result = null;
        try {
            ObjectMapper objectMapper = BeanUtil.getObjectMapper();
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, cls);
            result = objectMapper.readValue(content, javaType);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 反序列化数组
     *
     * @param <T>
     * @param content json字符串
     * @param cls     目标类型
     * @return
     */
    public static <T> T[] deserializeArray(String content, Class<T> cls) {
        T[] result = null;
        try {
            ObjectMapper objectMapper = BeanUtil.getObjectMapper();
            JavaType javaType = objectMapper.getTypeFactory().constructArrayType(cls);
            result = objectMapper.readValue(content, javaType);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    public static Map<String, Object> convertToMap(JSONObject jsonObject) {
        if (jsonObject == null) {
            return null;
        }
        Map<String, Object> result = new HashMap<String, Object>();
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            Object value = entry.getValue();
            String key = entry.getKey();
            if (value == null) {
                result.put(key, null);
            } else if (value instanceof JSONObject) {
                result.put(key, convertToMap((JSONObject) value));
            } else if (value instanceof JSONArray) {
                result.put(key, convertToListMap((JSONArray) value));
            } else {
                result.put(key, value);
            }
        }
        return result;
    }

    public static List<Map<String, Object>> convertToListMap(JSONArray jsonArray) {
        if (jsonArray == null) {
            return null;
        }
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < jsonArray.size(); i++) {
            result.add(convertToMap(jsonArray.getJSONObject(i)));
        }
        return result;
    }

    public static List<Map<String, Object>> convertToListMap(String json) {
        if (json == null || json.length() == 0) {
            return null;
        }
        try {
            if (json.trim().startsWith("[")) {
                JSONArray jsonArray = JSON.parseArray(json);
                return convertToListMap(jsonArray);
            } else {
                List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
                result.add(convertToMap(json));
                return result;
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static Map<String, Object> convertToMap(String json) {
        if (json == null || json.trim().length() == 0) {
            return null;
        }
        try {
            return convertToMap(JSON.parseObject(json));
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}